<template>
    <div class="chart-container">
        <h3 class="chart-title">{{ title }}</h3>
        <div ref="chart" class="chart-canvas"></div>
    </div>
</template>

<script>
import { ref, onMounted, onBeforeUnmount, watch } from 'vue';
import * as echarts from 'echarts';

export default {
    props: {
        option: {
            type: Object,
            required: true
        },
        title: {
            type: String,
            default: '图表'
        }
    },
    setup(props) {
        const chart = ref(null);
        let chartInstance = null;

        const initChart = () => {
            if (chart.value) {
                chartInstance = echarts.init(chart.value);
                chartInstance.setOption(props.option);
            }
        };

        const resizeChart = () => {
            chartInstance?.resize();
        };

        onMounted(() => {
            initChart();
            window.addEventListener('resize', resizeChart);
        });

        onBeforeUnmount(() => {
            if (chartInstance) {
                chartInstance.dispose();
                chartInstance = null;
            }
            window.removeEventListener('resize', resizeChart);
        });

        watch(() => props.option, (newOption) => {
            if (chartInstance) {
                chartInstance.setOption(newOption);
            }
        }, { deep: true });

        return {
            chart
        };
    }
};
</script>

<style scoped>
.chart-canvas {
    width: 100%;
    height: 300px;
}
</style>